﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CodeTop.复习九月份
{
    public class Solution42
    {
        public int Trap(int[] height)
        {
            int len = height.Length;

            int left = 0;
            int right = len - 1;

            int leftMax = height[left];
            int rightMax = height[right];
            int sum = 0;
            while (left < right)
            {
                if (leftMax < rightMax)//这个时候看left，因为right的左边还没有遍历到
                {
                    sum += leftMax - height[left];
                    left++;
                    leftMax = Math.Max(leftMax, height[left]);
                    //必须先left++;，再更新leftMax，否则height[left]>leftMax,有负数
                    Console.WriteLine("  leftMax:  " + leftMax + "height[left]:  " + height[left]);
                }
                else
                {
                    sum += rightMax - height[right];
                    right--;
                    rightMax = Math.Max(rightMax, height[right]);
                    Console.WriteLine("  rightMax:  " + rightMax + "height[right]:  " + height[right]);
                }
                Console.WriteLine(sum);
            }
            return sum;
        }
    }
}